<?php

namespace Common\Model;
use Think\Model;

class UserHospitalModel extends Model {

	protected $tableName = 'user_hospital';

	protected $_validate = array(
		['phone','/^1[34578]\d{9}$/','手机号不正确'],
    ['phone','','手机号不能重复',self::MUST_VALIDATE ,'unique'],
    ['password','require','需要填写密码',self::MUST_VALIDATE],
    ['password','/\w{6,18}/','密码应为6-18位数字字母或_',self::MUST_VALIDATE],
   );

 	protected $_auto = array (
 		['create_time','time',self::MODEL_INSERT,'function'],
 		['password','getPassword',self::MODEL_INSERT,'callback'],
  );

 	/**
 	 * 生成密码
 	 */
 	public function getPassword($password){
 		return md5(C('PASSWORD_SALT').$password);
 	}

  /**
   * 判断用户是否存在
   * @return boolean [description]
   */
  public function isPhoneExist($phone){
    return (boolean)$this->where(['phone'=>$phone])->find();
  }

  /**
   * 获取token
   */
  public function getToken(){

    if(!$this->token){
      return $this->makeToken();
    }

    return $this->token;
  }

  /**
   * 生成token并保存
   */
  public function makeToken(){
    $token = md5(uniqid().time());
    $this->token = $token;
    $this->save();
    return $token;
  }

  /**
   * 通过医院id，科室id，返回用户环信账号
   */
  public function getHospitalHuanxinId($hospitalId,$keshiId){
    $res = $this->where(['hospital_id'=>$hospitalId,'keshi_id'=>$keshiId])->getField('id',true);
    if(empty($res)){
      return [];
    }else{
      foreach($res as &$user){
        $user = C("HUANXIN_HOSPITAL_USER_PREFIX").$user;
      }
      return $res;
    }
  }

  public function getHospitalHuanxinIdByKeshiRelationId($relation_id){
    $res = M('HospitalKeshi')->find($relation_id);
    if(empty($res)){
      return [];
    }

    return $this->getHospitalHuanxinId($res['hospital_id'],$res['keshi_id']);
  }

  public function getHospitalHuanxinIdByKeshiRelationIdList($list){
    $res = [];
    foreach($list as $item){
      $huanxinidList = $this->getHospitalHuanxinIdByKeshiRelationId($item);
      $res = array_merge($res,$huanxinidList);
    }

    return $res;
  }

}